﻿using Mes.采购管理.model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;
namespace Mes.采购管理
{
    public partial class Purchaseshow : Form
    {
        public Purchaseshow()
        {
            InitializeComponent();
            SetupDataGridView();
        }

        private void SetupDataGridView()
        {
            datashow.AutoGenerateColumns = false; // 改为false，使用设计器中定义的中文列
            datashow.AllowUserToAddRows = false;
            datashow.ReadOnly = true;
            datashow.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 添加下面这行代码来隐藏行标题列
            datashow.RowHeadersVisible = false;
            // 添加序号列自动递增事件
            datashow.RowPostPaint += new DataGridViewRowPostPaintEventHandler(datashow_RowPostPaint);
            // 添加CellFormatting事件处理器，用于根据审批状态禁用审批按钮
            datashow.CellFormatting += new DataGridViewCellFormattingEventHandler(datashow_CellFormatting);
        }

        // 在SetupDataGridView方法之后添加CellFormatting事件处理方法
        private void datashow_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是审批按钮列
            if (e.ColumnIndex == datashow.Columns["Review"].Index && e.RowIndex >= 0)
            {
                // 获取当前行的数据
                WarehouseModel model = datashow.Rows[e.RowIndex].DataBoundItem as WarehouseModel;
                if (model != null && model.Approval == "已通过")
                {
                    // 设置按钮为禁用状态的视觉提示
                    e.CellStyle.ForeColor = Color.Gray; // 灰色文字
                    e.CellStyle.SelectionForeColor = Color.Gray; // 选中时也是灰色
                }
                else
                {
                    // 恢复默认样式
                    e.CellStyle.ForeColor = datashow.DefaultCellStyle.ForeColor;
                    e.CellStyle.SelectionForeColor = datashow.DefaultCellStyle.SelectionForeColor;
                }
            }
        }

        // 修改Purchaseshow_Load方法，将窗口设置为正常状态
        private void Purchaseshow_Load(object sender, EventArgs e)
        {
            // 移除或注释掉最大化设置，改为正常窗口状态
            // this.WindowState = FormWindowState.Maximized;
            this.WindowState = FormWindowState.Normal;
            Console.WriteLine("窗体加载完成");
        
            // 初始化查询条件下拉框
            cmbSearchField.Items.AddRange(new string[] {
                "采购编号", "采购状态",
        });
            cmbSearchField.SelectedIndex = 0;
        
            // 设置数据表格控件的锚点，使其随窗口大小调整
            datashow.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
        
            LoadWarehouseData();
        }
        
        // 添加窗口大小变化事件处理程序
        private void Purchaseshow_Resize(object sender, EventArgs e)
        {
            // 确保datashow控件随窗口大小调整
            if (datashow != null)
            {
                // 设置datashow控件的大小为窗口客户区的大小
                // 可以根据需要调整边距
                datashow.Size = new Size(
                    this.ClientSize.Width - 20,  // 左右边距各10
                    this.ClientSize.Height - 100  // 顶部和底部边距
                );
            }
        }
        // 在类里面添加这些变量来记录分页信息
        private int currentPage = 1;      // 当前页码
        private int pageSize = 15;        // 每页显示条数
        private int totalCount = 0;       // 总数据条数
        private int totalPages = 0;       // 总页数
        // 修改LoadWarehouseData方法，添加分页参数
        // 在文件顶部添加对login类的引用
       
        // 在文件顶部添加必要的命名空间

        
        
        private async void LoadWarehouseData(string keyword = "", string searchField = "")
        {
            try
            {
                string apiField = MapSearchField(searchField);
                string apiUrl = $"http://10.223.8.9:8082/api/Purchase/GetPurchaseList?PageIndex={currentPage}&PageSize={pageSize}";
                if (!string.IsNullOrEmpty(keyword))
                {
                    apiUrl += $"&{apiField}={Uri.EscapeDataString(keyword)}";
                }
        
                Console.WriteLine("请求API: " + apiUrl);
        
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }
        
                    // 发送GET请求并获取响应
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("API响应:\n" + jsonResponse);
        
                    JObject jsonObject = JObject.Parse(jsonResponse);
        
                    if (jsonObject["code"]?.Value<int>() == 200 && jsonObject["data"] != null)
                    {
                        // 解析分页信息
                        totalCount = jsonObject["data"]?["totalCount"]?.Value<int>() ?? 0;
                        totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                        UpdatePaginationDisplay();
        
                        // 解析数据
                        var itemsToken = jsonObject["data"]?["items"];
                        List<WarehouseModel> dataList = new List<WarehouseModel>();
        
                        if (itemsToken != null)
                        {
                            switch (itemsToken.Type)
                            {
                                case JTokenType.Array:
                                    dataList = itemsToken.ToObject<List<WarehouseModel>>();
                                    break;
                                case JTokenType.Object:
                                    dataList.Add(itemsToken.ToObject<WarehouseModel>());
                                    break;
                            }
                        }
        
                        // 调试：打印数据条数
                        Console.WriteLine($"解析到 {dataList.Count} 条数据");
        
                        // 绑定数据（需要在UI线程上执行）
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new Action(() =>
                            {
                                datashow.DataSource = null; // 清空数据源
                                if (dataList.Count > 0)
                                {
                                    datashow.DataSource = dataList;
                                }
                                else
                                {
                                    MessageBox.Show("没有找到数据", "提示");
                                }
                            }));
                        }
                        else
                        {
                            datashow.DataSource = null; // 清空数据源
                            if (dataList.Count > 0)
                            {
                                datashow.DataSource = dataList;
                            }
                            else
                            {
                                MessageBox.Show("没有找到数据", "提示");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show($"API返回错误: {jsonObject["message"]?.Value<string>() ?? "未知错误"}", "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }
        // 传统 switch 映射方法
        private string MapSearchField(string searchField)
        {
            switch (searchField)
            {
                case "采购状态":
                    return "Status";
                case "采购编号":
                    return "Reqest_No";
                default:
                    return "Reqest_No";
            }
        }
        // 更新分页信息显示
        private void UpdatePaginationDisplay()
        {
            // 更新页码文本框
            txtCurrentPage.Text = currentPage.ToString();
            txtPageSize.Text = pageSize.ToString();

            // 更新总页数显示
            lblTotalPages.Text = $"共 {totalPages} 页";
            lblTotalCount.Text = $"共 {totalCount} 条记录";

            // 控制按钮状态
            btnPrevPage.Enabled = currentPage > 1;
            btnNextPage.Enabled = currentPage < totalPages;
        }

        // 上一页按钮点击
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                LoadWarehouseData(); // 重新加载数据
            }
        }

        // 下一页按钮点击
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (currentPage < totalPages)
            {
                currentPage++;
                LoadWarehouseData(); // 重新加载数据
            }
        }

        // 跳转按钮点击
        private void btnGoToPage_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtCurrentPage.Text, out int page) && page >= 1 && page <= totalPages)
            {
                currentPage = page;
                LoadWarehouseData();
            }
            else
            {
                MessageBox.Show("请输入有效的页码", "提示");
            }
        }
        // 查询按钮点击
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text.Trim();
            string searchField = cmbSearchField.SelectedItem?.ToString() ?? "采购编号";

            // 如果是按状态查询，转换状态值为后端需要的格式（如数字代码）
            if (searchField == "采购状态")
            {
                // 示例：将中文状态映射为数字代码（根据实际后端要求调整）
                Dictionary<string, string> statusMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            { "待采购", "待采购" },
            { "已采购", "已采购" },
            { "采购中", "采购中" },
            { "", "" } // 查询所有状态
        };

                if (!statusMap.TryGetValue(keyword, out string statusValue))
                {
                    MessageBox.Show("请输入有效的状态（如：待采购、已采购、采购中）", "提示");
                    return;
                }

                keyword = statusValue; // 使用映射后的值
            }

            Console.WriteLine($"查询条件: searchField={searchField}, keyword={keyword}");
            currentPage = 1;
            LoadWarehouseData(keyword, searchField);
        }


        // 每页条数改变
        private void txtPageSize_TextChanged(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageSize.Text, out int size) && size > 0 && size <= 100)
            {
                pageSize = size;
                currentPage = 1; // 重置到第一页
                LoadWarehouseData();
            }
        }


        // 序号列自动递增
        private void datashow_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // 计算当前页的起始序号
            int startIndex = (currentPage - 1) * pageSize;
            // 设置行号（当前页起始序号 + 当前行索引 + 1）
            string rowNumber = (startIndex + e.RowIndex + 1).ToString();
            // 获取绘图区域
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,
                datashow.RowHeadersWidth, e.RowBounds.Height);
            // 绘制行号
            TextRenderer.DrawText(e.Graphics, rowNumber, datashow.Font,
                rectangle, datashow.ForeColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        }
        
        private void datashow_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否点击了操作列
            if (e.ColumnIndex == datashow.Columns["colOperation"].Index && e.RowIndex >= 0)
            {
                // 获取选中行的数据
                WarehouseModel selectedModel = datashow.Rows[e.RowIndex].DataBoundItem as WarehouseModel;
                if (selectedModel == null)
                {
                    MessageBox.Show("无法获取选中的采购记录", "错误");
                    return;
                }

                // 确认删除
                DialogResult result = MessageBox.Show($"确定要删除采购编号为 {selectedModel.Reqest_No} 的记录吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    DeletePurchase(selectedModel.Id);
                }
            }
            else if (e.ColumnIndex == datashow.Columns["Details"].Index && e.RowIndex >= 0)
            {
                // 获取选中行的数据
                WarehouseModel selectedModel = datashow.Rows[e.RowIndex].DataBoundItem as WarehouseModel;
                if (selectedModel == null)
                {
                    MessageBox.Show("无法获取选中的采购记录", "错误");
                    return;
                }
                // 修改这里，传递采购编号
                Details detailsForm = new Details(selectedModel.Reqest_No);
                detailsForm.Show();
            }
            else if (e.ColumnIndex == datashow.Columns["Review"].Index && e.RowIndex >= 0)
            {
                // 获取选中行的数据
                WarehouseModel selectedModel = datashow.Rows[e.RowIndex].DataBoundItem as WarehouseModel;
                if (selectedModel == null)
                {
                    MessageBox.Show("无法获取选中的采购记录", "错误");
                    return;
                }
                // 修改这里，传递采购编号

                
                // 添加检查：如果审批状态为"已通过"，则不允许再次审批
                if (selectedModel.Approval == "已通过")
                {
                    MessageBox.Show("该采购单已通过审批，无法再次审批", "提示");
                    return;
                }
                
                // 原有的审批按钮逻辑
                Approval approvalForm = new Approval(selectedModel.Reqest_No);
                approvalForm.Show();
            }
            // 添加修改按钮的处理逻辑
            else if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                // 调试：显示当前点击的列名
                string columnName = datashow.Columns[e.ColumnIndex].Name;
                if (columnName == "Revise")
                {
                    // 获取选中行的数据
                    WarehouseModel selectedModel = datashow.Rows[e.RowIndex].DataBoundItem as WarehouseModel;
                    if (selectedModel == null)
                    {
                        MessageBox.Show("无法获取选中的采购记录", "错误");
                        return;
                    }
                    // 打开修改表单，传递采购编号
                    Revise reviseForm = new Revise(selectedModel.Reqest_No);
                    reviseForm.Show();
                    reviseForm.BringToFront(); // 确保窗体显示在最前面
                }
            }
        }

        // 删除采购记录
        private async void DeletePurchase(int purchaseId)
        {
            try
            {
                string apiUrl = $"http://10.223.8.9:8082/api/Purchase/DeletePurchase?Id={purchaseId}";
        
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
                request.Method = "POST"; // 使用 POST 方法
                request.ContentType = "application/json; charset=utf-8"; // 设置 Content-Type
                request.ContentLength = 0; // 显式设置 Content-Length 为 0（无请求体）
                request.Timeout = 10000; // 设置 10 秒超时
        
                // 添加Token认证头
                if (!string.IsNullOrEmpty(login.CurrentToken))
                {
                    request.Headers.Add("Authorization", $"Bearer {login.CurrentToken}");
                }
        
                // 发送请求并获取响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    string jsonResponse = reader.ReadToEnd();
                    JObject jsonObject = JObject.Parse(jsonResponse);

                    if (jsonObject["code"]?.Value<int>() == 200)
                    {
                        MessageBox.Show("删除成功", "提示");
                        LoadWarehouseData(); // 重新加载数据
                    }
                    else
                    {
                        MessageBox.Show($"删除失败: {jsonObject["message"]?.Value<string>() ?? "未知错误"}");
                    }
                }
            }
            catch (WebException ex)
            {
                // 捕获 WebException 并显示详细错误
                if (ex.Response !=null)
                {
                    using (var errorResponse = (HttpWebResponse)ex.Response)
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string errorText = reader.ReadToEnd();
                        MessageBox.Show($"删除失败: {errorText}", "错误");
                    }
                }
                else
                {
                    MessageBox.Show($"删除失败: {ex.Message}", "错误");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败: {ex.Message}", "错误");
            }
        }

        // 在button1_Click方法后添加以下代码
        public void RefreshData()
        {
            
            // 重置页码为1
            currentPage = 1;
            // 刷新数据
            LoadWarehouseData();
            // 创建Purchase页面实例
           
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Purchase purchaseForm = new Purchase();
            // 显示页面
            purchaseForm.Show();
        }
    }
}

